package com.whut.whw.login;


import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.yoojia.fireeye.FireEye;
import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.bean.Users;
import com.whut.whw.model.BackResult;
import com.whut.whw.model.User;
import com.whut.whw.util.BackResultCallback;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.InputUtils;
import com.whut.whw.util.StringUtils;
import com.whut.whw.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.rong.imkit.RongIM;
import io.rong.imkit.widget.AutoLinkTextView;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

import static com.whut.whw.constant.ConfigConsts.Login_URL;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.coordinatorLayout)
    CoordinatorLayout coordinatorLayout;

    //校验器
    FireEye fireEye;
    //登录按钮
    @BindView(R.id.main_btn_login)
    TextView main_btn_login;
    //返回按钮
    @BindView(R.id.btn_back)
    ImageView btn_back;
    //注册按钮
    @BindView(R.id.main_btn__login_register)
    TextView main_btn_register;
    //忘记密码
    @BindView(R.id.main_btn_forgetPwd)
    AutoLinkTextView main_btn_forgetPwd;
    //用户名
    @BindView(R.id.login_username)
    EditText login_username;
    //密码
    @BindView(R.id.login_password)
    EditText login_password;
    //密码可见或者不可见
    @BindView(R.id.pwd_visible_invisible)
    ImageView pwd_visible_invisible;
    //用户名
    String username;
    String password;
    //密码

    private List<Users> list;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        //输入控制-->不允许输入空格
        InputUtils.setEditTextInhibitInputSpace(login_username);
        InputUtils.setEditTextInhibitInputSpace(login_password);
        //长度限制
        InputUtils.setEditTextMaxLength(login_username, 20);
        InputUtils.setEditTextMaxLength(login_password, 20);

        //获取userinfo中的数据
        SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
        Log.e("TC", sp.getString("nc", ""));
        Log.e("TC", sp.getString("mm", ""));
        login_username.setText(sp.getString("nc", ""));
        login_password.setText(sp.getString("mm", ""));
    }

    @Override
    public void setListener() {
        main_btn_login.setOnClickListener(new Login_listener());//监听登录事件
        btn_back.setOnClickListener(new Back_listener());//监听返回事件
        main_btn_register.setOnClickListener(new Register_listener());//监听注册事件
        main_btn_forgetPwd.setOnClickListener(new ForgetPwd_listener());//监听忘记密码事件
        pwd_visible_invisible.setOnClickListener(new Visible_invisible_pwd_listener());
    }

    //登录
    private class Login_listener implements View.OnClickListener {

        @Override
        public void onClick(View v) {

            if (loginCheck()) {
                OkHttpUtils
                        .post()
                        .url(Login_URL)
                        .addParams("name", username)
                        .addParams("password", password)
                        .build()
                        .execute(new BackResultCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                getUiDelegate().toastLong(e.toString());
                                Log.e("TC", e.toString());
                            }

                            @Override
                            public void onResponse(BackResult response, int id) {
                                //提示信息
                                Snackbar.make(coordinatorLayout, response.getMsg(), Snackbar.LENGTH_LONG).show();
                                //如果登录成功
                                if (response.isSuccess()) {
                                    loginSuccess(response);
                                }
                            }
                        });
            }
        }

    }

    /**
     * 登录校验
     *
     * @return
     */
    private boolean loginCheck() {
        username = login_username.getText().toString().trim();
        password = login_password.getText().toString().trim();
        if (StringUtils.isTrimEmpty(username)) {
            Snackbar.make(coordinatorLayout, getResources().getString(R.string.enter_username_ck), Snackbar.LENGTH_LONG).show();
            return false;
        }
        if (StringUtils.isTrimEmpty(password)) {
            Snackbar.make(coordinatorLayout, getResources().getString(R.string.enter_pwd_ck), Snackbar.LENGTH_LONG).show();
            return false;
        }
        if (password.length() < 6) {
            Snackbar.make(coordinatorLayout, getResources().getString(R.string.pwd_length_ck), Snackbar.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    /**
     * 登录成功
     *
     * @param response
     */
    private void loginSuccess(BackResult response) {
        Log.e("TC", response.getData());
        try {
            //将返回的结果转换成User对象
            User user = GsonUtils.GsonToBean(response.getData(), User.class);
            Log.e("TC", user.toString());
            //将昵称、密码、token写入文件中
            SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
            SharedPreferences.Editor ed = sp.edit();
            Log.e("TC", user.getNc());
            Log.e("TC", user.getMm());
            Log.e("TC", user.getToken());
            ed.putString("yhbh",user.getYhbh());
            ed.putString("nc", user.getNc());
            ed.putString("mm", user.getMm());
            ed.putString("token", user.getToken());
            ed.commit();
            connectRong(user.getToken());
        } catch (Exception e) {
            Log.e("TC", e.toString());
            e.printStackTrace();
        }
    }

    /**
     * 连接融云
     *
     * @param token
     */
    private void connectRong(String token) {
        /**
         * 测试
         */
        list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("user_id", "123456");
            obj.put("user_name", "忘尘无憾");
            obj.put("user_img", "http://upload.jianshu.io/users/upload_avatars/3358298/167277b0-84f6-4b2c-a740-d117ab4687b6.jpg");
            array.put(obj);
            JSONObject obj1 = new JSONObject();
            obj1.put("user_id", "111");
            obj1.put("user_name", "若忘尘");
            obj1.put("user_img", "https://ss3.baidu.com/7LsWdDW5_xN3otqbppnN2DJv/pass/s%3D110%3Bq%3D90%3Bg%3D0/sign=e233f4b84a4a20a4351e38c6a069e91f/08f790529822720eadd64e507ecb0a46f21fab04.jpg");
            array.put(obj1);
            list = GsonUtils.jsonToList(array.toString(), Users.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                Toast.makeText(LoginActivity.this, "onTokenIncorrect", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String s) {

                RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                    @Override
                    public UserInfo getUserInfo(String s) {
                        for (Users user : list) {
                            if (user.getUser_id().equals(s)) {
                                return new UserInfo(user.getUser_id(), user.getUser_name(), Uri.parse(user.getUser_img()));
                            }
                        }
                        return null;
                    }
                }, true);
                Toast.makeText(LoginActivity.this, "RongYun Connect Success", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Toast.makeText(LoginActivity.this, "RongYun Connect Fail", Toast.LENGTH_SHORT).show();
            }
        });
    }


    //返回
    private class Back_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            finish();
        }
    }

    //注册事件
    private class Register_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
            finish();
        }
    }

    //忘记密码
    private class ForgetPwd_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            ToastUtils.showShort("您点击了忘记密码事件");
            SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
            getUiDelegate().toastLong(sp.getString("nc", ""));
        }
    }

    //监听密码可见或者不可见事件
    private class Visible_invisible_pwd_listener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // ToastUtils.showShort("您点击了图标");
            if (login_password.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                login_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                //v.setBackgroundResource(R.mipmap.pwd_visible);
                pwd_visible_invisible.setImageResource(R.mipmap.pwd_invisible);
            } else {
                login_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                pwd_visible_invisible.setImageResource(R.mipmap.pwd_visible);
            }
        }

    }
}
